/**
 * jims
 */
package com.jims.master.modules.drug.web;

import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.BaseController;
import com.jims.master.modules.drug.entity.*;
import com.jims.master.modules.drug.service.DrugExportService;
import com.jims.master.modules.drug.service.DrugStockService;
import com.jims.master.modules.drug.service.DrugStorageDeptService;
import com.jims.master.modules.drug.service.DrugSupplierCataService;
import com.jims.master.modules.sys.entity.OrgDept;
import com.jims.master.modules.sys.service.OrgDeptService;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.utils.DrugUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 药品库存管理Controller
 *
 * @author zhuq
 * @version 2017-03-10
 */
@Controller
@RequestMapping(value = "${adminPath}/drug/drugStock")
public class DrugStockController extends BaseController {

    @Autowired
    private DrugStockService drugStockService;
    @Autowired
    private DrugStorageDeptService drugStorageDeptService;
    @Autowired
    private OrgDeptService orgDeptService;
    @Autowired
    private DrugSupplierCataService drugSupplierCataService;
    @Autowired
    private DrugExportService drugExportService;


    @ModelAttribute
    public DrugStock get(@RequestParam(required = false) String id) {
        DrugStock entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = drugStockService.get(id);
        }
        if (entity == null) {
            entity = new DrugStock();
        }
        return entity;
    }

    /**
     * 批量入库首页
     *
     * @param
     * @param request
     * @param response
     * @param model
     * @return
     * @author fengyg
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"batchImport", ""})
    public String batchImport(DrugExportMaster drugExportMaster, HttpServletRequest request, HttpServletResponse response, Model
            model) {
        drugExportMaster.setReceiver(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        Page<DrugExportMaster> page = drugExportService.batchImport(new Page<DrugExportMaster>(request, response), drugExportMaster);
        model.addAttribute("drugExportMaster", drugExportMaster);
        model.addAttribute("page", page);
        return "modules/drug/drugImportBatch";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = {"index", ""})
    public String list(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<DrugStock> page = drugStockService.findPage(new Page<DrugStock>(request, response), drugStock);
        model.addAttribute("page", page);
        return "modules/drug/drugStockIndex";
    }

    /**
     * 药品对消入出库跳转
     * @return
     * @author ZYG
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"drugInOutIndex", ""})
    public String ieList(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<DrugStock> page = drugStockService.findPage(new Page<DrugStock>(request, response), drugStock);
        model.addAttribute("page", page);
        return "modules/drug/drugInOutIndex";
    }

    /**
     * 药品对消入出库添加表格
     * @return
     * @author ZYG
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "drugInOutForm")
    public String drugInOutForm(DrugStock drugStock, Model model) {
        model.addAttribute("drugStock", drugStock);
        return "modules/drug/drugInOutForm";
    }
    /**
     * 药品对消入出库保存
     * @param list
     * @param request
     * @param response
     * @return
     * @author ZYG
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "saveInOutDrug")
    @ResponseBody
    public StringData saveInOutDrug(@RequestBody List<DrugStock> list, HttpServletRequest request, HttpServletResponse response) {
        StringData data = new StringData();
        int t = drugStockService.ifStockExist(list);//判断当前科室是否存在库房，存在才能入库出库
        if(t>0){
            int i = drugStockService.saveInOutDrug(list);
            if (i > 0) {
                data.setCode("success");
                data.setData("对消入出库成功");
            } else {
                data.setCode("error");
                data.setData("对消入出库失败");
            }
        }
       else{
            data.setCode("no");
            data.setData("当前科室不存在库房，无法进行该操作！");
        }
        return data;
    }

    /**
     * @param drugInfo 传递参数
     * @return List<DrugInfo> 返回类型
     * @throws
     * @Title: autoCompletePrice
     * @Desciption: (药品出库选择有库存有价格的药品自动补全)
     * @author fengyg
     * @date 2017-03-17
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"autoDrugInOut", ""})
    @ResponseBody
    public List<DrugExportDetail> autoDrugInOut(String q, String limit, DrugInfo drugInfo) {
        if (q != null && !q.equals("")) {
            try {
                q = URLDecoder.decode(q, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        List<DrugExportDetail> list = drugStockService.autoDrugInOut(drugInfo, UserUtils.getOrgId(), q, limit);
        return list;
    }

    /**
     * 药品销售记录查询
     * @return
     * @author ZYG
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"drugFlowAccount", ""})
    public String drugFlowAccount(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<DrugStock> page = drugStockService.findAccountPage(new Page<DrugStock>(request, response), drugStock);
        model.addAttribute("page", page);
        return "modules/drug/drugFlowAccountIndex";
    }
    /**
     * 药品销售记录查询(退药)
     * @return
     * @author ZYG
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"drugFlowAccountBack", ""})
    public String drugFlowAccountBack(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<DrugStock> page = drugStockService.findAccountPageBack(new Page<DrugStock>(request, response), drugStock);
        model.addAttribute("page", page);
        return "modules/drug/drugFlowAccountIndex";
    }
    @RequiresPermissions("user")
    @RequestMapping(value = {"query", ""})
    public String listquery(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response, Model
            model, String drugName, String drugType) {
        drugStock.setStorageId(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        Page<DrugStock> page = drugStockService.findDrugList(new Page<DrugStock>(request, response), drugStock,
                drugName, drugType);
        List<DrugStorageDept> list = drugStorageDeptService.findList(new DrugStorageDept());
        List<OrgDept> lowLevelDeptList = orgDeptService.getLowLevelDeptList();

        model.addAttribute("page", page);
        model.addAttribute("list", list);
        return "modules/drug/drugStockQuery";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = {"stockSizeQuery", ""})
    public String listque(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response, Model model) {
        return "modules/drug/drugStockQuery";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = {"queryBat", ""})
    public String listquerybat(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response, Model
            model) {
        drugStock.setStorageId(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        Page<DrugStock> page = drugStockService.findDrugListbat(new Page<DrugStock>(request, response), drugStock);
        List<DrugStorageDept> list = drugStorageDeptService.findList(new DrugStorageDept());
        model.addAttribute("list", list);
        model.addAttribute("page", page);
        return "modules/drug/drugStockQuery";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = {"queryAll", ""})
    public String listqueryAll(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response, Model
            model, String drugName, String drugType) {
        List<DrugStorageDept> list = drugStorageDeptService.findList(new DrugStorageDept());
        Page<DrugStock> page = drugStockService.findDrugList(new Page<DrugStock>(request, response), drugStock,
                drugName, drugType);
        model.addAttribute("page", page);
        model.addAttribute("list", list);
        List<DrugSupplierCata> firmList = drugSupplierCataService.findList(new DrugSupplierCata());
        model.addAttribute("firmList", firmList);
        return "modules/drug/drugAllStockQuery";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = {"queryAllBat", ""})
    public String listqueryAllbat(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response,
                                  Model model) {
        Page<DrugStock> page = drugStockService.findDrugListbat(new Page<DrugStock>(request, response), drugStock);
        model.addAttribute("page", page);
        List<DrugStorageDept> list = drugStorageDeptService.findList(new DrugStorageDept());
        model.addAttribute("list", list);
        List<DrugSupplierCata> firmList = drugSupplierCataService.findList(new DrugSupplierCata());
        model.addAttribute("firmList", firmList);
        return "modules/drug/drugAllStockQuery";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = "form")
    public String form(DrugStock drugStock, Model model) {
        model.addAttribute("drugStock", drugStock);
        return "modules/drug/drugStockForm";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = "save")
    @ResponseBody
    public StringData save(DrugStock drugStock, Model model) {
        StringData data = new StringData();
        drugStock.updateOrgId();
        int i = drugStockService.save(drugStock);
        if (i > 0) {
            data.setCode("success");
            data.setData("保存药品入库成功");
        } else {
            data.setCode("error");
            data.setData("保存药品入库失败");
        }
        return data;
    }

    @RequiresPermissions("user")
    @RequestMapping(value = "delete")
    @ResponseBody
    public StringData delete(DrugStock drugStock) {
        StringData data = new StringData();
        int i = drugStockService.delete(drugStock);
        if (i > 0) {
            data.setCode("success");
            data.setData("删除药品入库成功");
        } else {
            data.setCode("error");
            data.setData("删除药品入库失败");
        }
        return data;
    }

    /*药品入库处理
    * @zhuq
    * 获取要入库的drugList,分别插入drugStock,drugImportMaster,drugImportDetail表
    * */
    @RequiresPermissions("user")
    @RequestMapping(value = "importDrug")
    @ResponseBody
    public StringData saveImportDrug(@RequestBody List<DrugStock> drugStockList, HttpServletRequest request,
                                     HttpServletResponse response) {
        StringData data=new StringData();
        String printMasterId=drugStockService.saveImportDrug(drugStockList);
        if(printMasterId!="0"){
            data.setCode("success");
            data.setData(printMasterId);
        }else{
            data.setCode("error");
            data.setData("入库失败");
        }
        return data;
    }

    /**
     * 药品批量入库
     *
     * @param request
     * @param response
     * @return
     * @author fengyg
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "saveBatchImport")
    @ResponseBody
    public StringData saveBatchImport(DrugImportMaster drugImportMaster, HttpServletRequest request,
                                      HttpServletResponse response) {
        StringData stringData = new StringData();
        stringData = drugStockService.saveBatchImport(drugImportMaster);
        return stringData;
    }

    /**
     * 根据传递过来的入出库类别返回供货方集合
     *
     * @param type     入出库类别,如果是采购，那么返回生产商供应商集合;如果是其他,返回库房集合
     * @param request
     * @param response
     * @return
     * @author fengyg
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"getSupplierList", ""})
    @ResponseBody
    public List<DrugStock> getSupplierList(String type, HttpServletRequest request, HttpServletResponse response,
                                           Model model) {
        List list = DrugUtils.getSupplierOrStorageList(type);
        List<DrugStock> stockList = new ArrayList<DrugStock>();
        if (null != list && list.size() > 0) {
            if (type.equals("采购") || type.equals("0")) {
                for (int i = 0; i < list.size(); i++) {
                    DrugStock stock = new DrugStock();
                    stock.setDrugSupplierCata((DrugSupplierCata) list.get(i));
                    stockList.add(stock);
                }
            } else {
                for (int i = 0; i < list.size(); i++) {
                    DrugStock stock = new DrugStock();
                    stock.setDrugStorageDept((DrugStorageDept) list.get(i));
                    stockList.add(stock);
                }
            }
        }
        return list;
    }

    /**
     * 根据drugInfoId、storageId获取当前库房下的不同批次库存大于0的list
     *
     * @return
     * @author zhuq
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"findByInfoId", ""})
    public String saveBatchImport(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response,
                                  Model model) {
        List<DrugStock> drugStockList = drugStockService.findByInfoId(drugStock);
        model.addAttribute("drugStockList", drugStockList);
        return "modules/drug/drugInventoryCheckForm";
    }

    /**
     *根据visitId 获取待退费医嘱药品list
     * @return
     * @author zhuq
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"findByVisitId", ""})
    public String findByVisitId(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response,
                                  Model model) {
        drugStock.setStorageId(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        drugStock.updateOrgId();
        drugStock.setRemarks("1");
        List<DrugStock> drugStockList = drugStockService.findByVisitId(drugStock);
        model.addAttribute("drugStockList", drugStockList);
        model.addAttribute("drugStock", drugStock);
        return "modules/drugOut/ordersDrugInForm";
    }

    /**
     *根据visitId 获取已退费医嘱药品list
     * @return
     * @author zhuq
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"findByVisitIdForm", ""})
    public String findByVisitIdForm(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response,
                                Model model) {
        drugStock.setStorageId(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        drugStock.updateOrgId();
        drugStock.setRemarks("2");
        List<DrugStock> drugStockList = drugStockService.findByVisitId(drugStock);
        model.addAttribute("drugStockList", drugStockList);
        model.addAttribute("drugStock", drugStock);
        return "modules/drugOut/ordersDrugInRecordForm";
    }

    /**
     *根据visitId 获取待退医嘱的药品并进行退库存，退药
     * @return
     * @author zhuq
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"inpInStock"})
    @ResponseBody
    public StringData inpInStock(DrugStock drugStock, HttpServletRequest request, HttpServletResponse response,
                                    Model model) {
        drugStock.setStorageId(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        drugStock.updateOrgId();
        drugStock.setRemarks("1");
        StringData data=new StringData();
        int num=drugStockService.inpInStock(drugStock);
        if(num==1){
            data.setCode("success");
            data.setData("退药成功");
        }else{
            data.setCode("error");
            data.setData("退药失败");
        }
        return data;
    }

}